package choosebutton;

import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 * 
 * @author signsmile
 * @version
 * 
 * 用法jTextField.setSize(300, 100);
		jTextField.setEnabled(false);
		jTextField.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int x = (int) (getFrame().getLocation().getX()+ jTextField.getLocation().getX());
				int y = (int) (getFrame().getLocation().getY()+ jTextField.getLocation().getY() + 50D);
				MyDateChooser w = MyDateChooser.getInstance(x, y, getFrame(),jTextField);
				w.showDialog(true);
			}
		});
		this.add(jTextField);
 */
public class MyDateChooser extends JWindow implements ChangeListener {
	private static final long serialVersionUID = 1L;
	private static final int width = 230; // 界面宽度
	private static final int height = 192; // 界面高度

	//private static final Color backGroundColor = Color.gray; // 底色
	// 月历表格配色----------------//
	private static final Color palletTableColor = Color.white; // 日历表底色
	private static final Color todayBackColor = Color.orange; // 今天背景色
	private static final Color weekFontColor = Color.blue; // 星期文字色
	private static final Color dateFontColor = Color.black; // 日期文字色
	private static final Color weekendFontColor = Color.red; // 周末文字色
	private static final Color BorderColor = Color.black; // 边框色
	// 控制条配色------------------//
	private static final Color controlLineColor = Color.pink; // 控制条底色
	private static final Color controlTextColor = Color.white; // 控制条标签文字色
	private static final Color rbBorderColor = Color.red; // 控制条边框色

	private static final String YEAR = "年";
	private static final String MONTH = "月";
//	private static final String WEEK_SUN = "日";
//	private static final String WEEK_MON = "一";
//	private static final String WEEK_TUE = "二";
//	private static final String WEEK_WED = "三";
//	private static final String WEEK_THU = "四";
//	private static final String WEEK_FRI = "五";
//	private static final String WEEK_SAT = "六";
	private static final String title[] = { "日", "一", "二", "三", "四", "五", "六" };
	private int x, y;
	private int todayOfMonth;
	private JSpinner sprYYYY, sprMM;
	private JTable dateTable;
	private DefaultTableModel dateTableMd;
	private JTextField jTextField;

	private static MyDateChooser myDateChooser;

	private MyDateChooser() {
	}

	private MyDateChooser(int x, int y, Window owner, JTextField jTextField) {
		super(owner);
		try {
			viewInit();
			this.jTextField = jTextField;
			this.setBounds(x, y, width, height);
			this.setVisible(true);
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}

	public static MyDateChooser getInstance(int x, int y, Window owner,
			JTextField jTextField) {
		if (myDateChooser == null)
			myDateChooser = new MyDateChooser(x, y, owner, jTextField);
		else
			myDateChooser.setLocation(x, y);
		return myDateChooser;
	}

	private void viewInit() {
		JPanel jpNorth = new JPanel();
		jpNorth.setFont(new Font("宋体", Font.PLAIN, 12));// 设置固定字体，以免调用环境改变影响界面美观
		jpNorth.setBorder(BorderFactory.createLineBorder(Color.black));
		jpNorth.setBounds(new Rectangle(6, 7, 217, 27));
		jpNorth.setBackground(controlLineColor);
		jpNorth.setLayout(new GridLayout(1, 7));

		JLabel cell;
		for (int i = 0; i < 7; i++) {
			cell = new JLabel(title[i]);
			cell.setHorizontalAlignment(JLabel.CENTER);
			if (i == 0 || i == 6)
				cell.setForeground(weekendFontColor);
			else
				cell.setForeground(weekFontColor);
			jpNorth.add(cell);
		}

		JPanel jpSouth = new JPanel();
		jpSouth.setBounds(new Rectangle(6, 155, 217, 30));
		jpSouth.setLayout(new FlowLayout());
		jpSouth.setBackground(controlLineColor);
		sprYYYY = new JSpinner();
		sprYYYY.setEditor(new JSpinner.NumberEditor(sprYYYY, "####"));
		sprYYYY.setBorder(BorderFactory.createLineBorder(rbBorderColor));
		jpSouth.add(sprYYYY);
		JLabel jLbyear = new JLabel(YEAR);
		jLbyear.setForeground(controlTextColor);
		jpSouth.add(jLbyear);
		sprMM = new JSpinner();
		sprMM.setBorder(BorderFactory.createLineBorder(rbBorderColor));
		jpSouth.add(sprMM);
		JLabel jLbMonth = new JLabel(MONTH);
		jLbMonth.setForeground(controlTextColor);
		jpSouth.add(jLbMonth);

		dateTable = new JTable();
		dateTable.setAutoscrolls(false);
		dateTable.setBorder(BorderFactory.createLineBorder(BorderColor));
		dateTable.setRequestFocusEnabled(false);
		dateTable.setRowHeight(20);
		dateTable.setBounds(new Rectangle(6, 34, 217, 120));
		dateTable.setRowSelectionAllowed(true);
		dateTable.setColumnSelectionAllowed(true);
		dateTable.setShowGrid(false);
		dateTable.setFont(new Font("楷体", Font.BOLD, 15));
		dateTable.setBackground(palletTableColor);
		dateTable.setForeground(dateFontColor);
		dateTable.setSelectionForeground(todayBackColor);

		// this.setAlwaysOnTop(true);
		this.getContentPane().setLayout(null);
		this.getContentPane().setBackground(SystemColor.inactiveCaption);

		this.getContentPane().add(dateTable, null);
		this.getContentPane().add(jpNorth, null);
		this.getContentPane().add(jpSouth, null);

		initDates();
		sprMM.addChangeListener(this);
		sprYYYY.addChangeListener(this);
		dateTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				Object value = dateTable.getValueAt(dateTable.getSelectedRow(),
						dateTable.getSelectedColumn());
				if (value != null)
					jTextField.setText((new StringBuilder()).append(
							sprYYYY.getValue()).append("-").append(
							sprMM.getValue()).append("-").append(value)
							.toString());
				if (e.getClickCount() == 2 && value != null)
					showDialog(false);
			}
		});
		drawTableColor();
	}

	private void initDates() {
		try {
			dateTableMd = new DefaultTableModel(printDates(), title) {
				private static final long serialVersionUID = 1L;

				public boolean isCellEditable(int pRow, int pCol) {
					return false;
				}
			};
			dateTable.setModel(dateTableMd);
			selectedCell(x, y);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void upDateDates(Object yyyy, Object mm) {
		try {
			dateTableMd = new DefaultTableModel(
					printDates((new StringBuilder()).append(yyyy).append("-")
							.append(mm).append("-").append(todayOfMonth)
							.toString()), title) {
				private static final long serialVersionUID = 1L;

				public boolean isCellEditable(int pRow, int pCol) {
					return false;
				}
			};
			dateTable.setModel(dateTableMd);
			selectedCell(x, y);
		} catch (Exception ex) {
		}
	}

	private void drawTableColor() {
		class MyCellRenderer extends DefaultTableCellRenderer {
			private static final long serialVersionUID = 1L;

			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus, int row,
					int column) {
				Component cell = super.getTableCellRendererComponent(table, value,
						isSelected, hasFocus, row, column);
				if (column == 0 || column == 6)
					cell.setForeground(weekendFontColor);
				else {
					cell.setForeground(dateFontColor);
				}
				return cell;
			}
		}
		MyCellRenderer myCellRenderer = new MyCellRenderer();
		myCellRenderer.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
		dateTable.setDefaultRenderer(dateTable.getColumnClass(1),myCellRenderer);
	}

	
	private void selectedCell(int row, int col) {
		row--;
		col--;
		dateTable.setRowSelectionInterval(row, row);
		dateTable.setColumnSelectionInterval(col, col);
	}

	private String[][] printDates() throws Exception {
		return printDates(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
	}

	private String[][] printDates(String str) throws Exception {
		Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
		Calendar d = Calendar.getInstance();
		d.setTime(date);
		sprYYYY.setValue(d.get(Calendar.YEAR));
		sprMM.setValue(Integer.valueOf(d.get(Calendar.MONTH) + 1));
		todayOfMonth = d.get(Calendar.DATE);

		d.set(Calendar.DATE, 1);
		int firstDate = d.get(Calendar.DAY_OF_WEEK);
		d.set(Calendar.DATE, todayOfMonth);
		int dateOfMax = d.getActualMaximum(Calendar.DATE);
		String mydate[][] = new String[6][7];
		int tmp = 0;
		int currentDate = 1;
		boolean flag = true;
		for (int i = 0; i < 6 && flag; i++) {
			for (int j = 1; j <= 7; j++) {
				if (++tmp < firstDate)
					continue;
				if (currentDate == todayOfMonth) {
					y = j;
					x = i + 1;
				}
				mydate[i][j - 1] = String.valueOf(currentDate);
				if (++currentDate <= dateOfMax)
					continue;
				flag = false;
				break;
			}

		}
		return mydate;
	}

	public void stateChanged(ChangeEvent e) {
		JSpinner o = (JSpinner) e.getSource();
		if (!o.equals(sprYYYY)) {
			int value = Integer.parseInt(String.valueOf(sprMM.getValue()));
			if (value < 1)
				sprMM.setValue(Integer.valueOf(12));
			if (value > 12)
				sprMM.setValue(Integer.valueOf(1));
		}
		upDateDates(sprYYYY.getValue(), sprMM.getValue());
	}

	public void showDialog(boolean showOrhide) {
		setVisible(showOrhide);
	}
}